package net.maku.project.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.project.convert.ProcessStagesConvert;
import net.maku.project.entity.ProcessStagesEntity;
import net.maku.project.query.ProcessStagesQuery;
import net.maku.project.vo.ProcessStagesVO;
import net.maku.project.dao.ProcessStagesDao;
import net.maku.project.service.ProcessStagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 流程阶段表
 *
 * @author 艾力 1106997025@qq.com
 * @since 1.0.0 2024-07-09
 */
@Service
@AllArgsConstructor
public class ProcessStagesServiceImpl extends BaseServiceImpl<ProcessStagesDao, ProcessStagesEntity> implements ProcessStagesService {

    @Autowired
    private ProcessStagesDao processStagesDao;
    @Override
    public PageResult<ProcessStagesVO> page(ProcessStagesQuery query) {
        IPage<ProcessStagesEntity> page = baseMapper.selectPage(getPage(query), getWrapper());

        return new PageResult<>(ProcessStagesConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private LambdaQueryWrapper<ProcessStagesEntity> getWrapper() {

        return Wrappers.lambdaQuery();
    }

    @Override
    public void save(ProcessStagesVO vo) {


        ProcessStagesEntity entity = ProcessStagesConvert.INSTANCE.convert(vo);
        entity.setId(null);
        baseMapper.insert(entity);
    }


    @Override
    public void update(ProcessStagesVO vo) {
        ProcessStagesEntity entity = ProcessStagesConvert.INSTANCE.convert(vo);
        updateById(entity);
    }

    // 更新流程阶段表的结束时间
    @Override
    public void updateStageEndTime(Long stageId, LocalDateTime endTime) {
        ProcessStagesEntity stage = new ProcessStagesEntity();
        stage.setId(stageId);
        stage.setEndTime(endTime);
        stage.setFinish(true);
        System.out.println("stage = " + stage + " ---endTime = " + endTime);
        updateById(stage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public List<ProcessStagesVO> getByProjectId(Long projectId) {
        List<ProcessStagesEntity> processStagesEntities = new LambdaQueryChainWrapper<>(baseMapper).eq(ProcessStagesEntity::getProjectId, projectId).list();
        return ProcessStagesConvert.INSTANCE.convertList(processStagesEntities);
    }

    @Override
    public LocalDateTime getStarTimeByProjectIdWithStage(Long projectId, String stageName) {
        ProcessStagesEntity stagesEntity = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ProcessStagesEntity::getProjectId, projectId)
                .eq(ProcessStagesEntity::getName, stageName)
                .last("limit 1").one();
        if (stagesEntity == null) {
            return null;
        }
        return stagesEntity.getStartTime();
    }

    @Override
    public ProcessStagesEntity getStageByProjectIdAndStageId(Long projectId, Long stageId) {
        return new LambdaQueryChainWrapper<>(baseMapper).eq(ProcessStagesEntity::getProjectId, projectId)
                .eq(ProcessStagesEntity::getConfigStageId, stageId).last("limit 1").one();
    }

    @Override
    public void updateNextStageStarTime(String nextStatusName, Long projectId) {

        // 首先检查nextStatusName是否为空，为空则直接返回
        if (StringUtils.isBlank(nextStatusName)) {
            return;
        }

        // 使用LambdaQueryChainWrapper构建查询条件
        final LambdaQueryChainWrapper<ProcessStagesEntity> queryWrapper = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ProcessStagesEntity::getProjectId, projectId)
                .eq(ProcessStagesEntity::getName, nextStatusName);

        // 执行查询并获取唯一结果
        ProcessStagesEntity processStagesEntity = queryWrapper.one();

        // 检查是否找到了匹配的实体，如果没有找到，则直接返回
        if (processStagesEntity == null) {
            return;
        }

        // 设置开始时间为当前时间
        processStagesEntity.setStartTime(LocalDateTime.now());

        // 使用LambdaUpdateChainWrapper构建更新条件
        final LambdaUpdateChainWrapper<ProcessStagesEntity> updateWrapper = new LambdaUpdateChainWrapper<>(baseMapper)
                .eq(ProcessStagesEntity::getProjectId, projectId)
                .eq(ProcessStagesEntity::getName, nextStatusName);

        // 执行更新操作
        updateWrapper.update(processStagesEntity);
    }

    @Override
    public boolean stageIsAllCompleted(Long projectId) {
        // 构建查询条件，查找projectId对应的记录
        LambdaQueryWrapper<ProcessStagesEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcessStagesEntity::getProjectId, projectId);

        // 获取所有符合条件的记录
        List<ProcessStagesEntity> stagesList = processStagesDao.selectList(queryWrapper);

        // 检查所有记录的finish字段是否都为true
        for (ProcessStagesEntity entity : stagesList) {
            if (!entity.getFinish()) { // 如果发现任何一个阶段未完成
                return false; // 直接返回false
            }
        }

        // 如果所有阶段都完成，则返回true
        return true;
    }
}




